package com.kun.demo04_synchronize.solution;


import org.junit.Test;

//买火车票问题，线程不安全
public class NotSafeCase1_buyTickets {

    private int tickets = 10;
    private boolean flag = true;

    class Ticket implements Runnable{
        @Override
        public void run() {
            while (flag){
                buyTicket();
            }

        }

//        public synchronized void buyTicket(){
//            if (tickets <= 0){
//                flag = false;
//                return;
//            }
//            try {
//                Thread.sleep(100);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//
//            System.out.println(Thread.currentThread().getName() + " 正在买第 " + tickets-- + " 张票...");
//        }
        public synchronized void buyTicket(){
            if (tickets <= 0){
                flag = false;
                return;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println(Thread.currentThread().getName() + " 正在买第 " + tickets-- + " 张票...");
        }
    }



    @Test
    public void test() throws InterruptedException {
        System.out.println("开始买票...");
        Ticket ticket = new Ticket();
        synchronized (ticket){
            new Thread(ticket, "A").start();
            new Thread(ticket, "B").start();
            new Thread(ticket, "C").start();
        }

        Thread.sleep(2000); // 延迟主线程退出
    }
}


